package com.orange.common.binding

import android.view.View
import android.view.View.NO_ID
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.databinding.BindingAdapter
import com.orange.common.ktx.onClick

object ViewAdapter {
    /**
     * 设置view的防抖点击事件
     */
    @JvmStatic
    @BindingAdapter("onClick")
    fun onClick(view: View, onClickListener: View.OnClickListener?) {
        if (onClickListener != null) {
            view.onClick {
                onClickListener.onClick(view)
            }
        }
    }

    /**
     * 设置view背景
     */
    @BindingAdapter("android:background")
    @JvmStatic
    fun setBackgroundRes(v: View, drawableId: Int) {
        if (drawableId > NO_ID) v.setBackgroundResource(drawableId) else v.background = null
    }

    /**
     * 设置是否 显示view
     */
    @JvmStatic
    @BindingAdapter("visibility")
    fun visibility(view: View, boolean: Boolean) {
        view.isVisible = boolean
    }

    /**
     * 设置是否 看不见view
     */
    @JvmStatic
    @BindingAdapter("invisible")
    fun invisible(view: View, boolean: Boolean) {
        view.isInvisible = boolean
    }

    /**
     * 设置是否 隐藏view
     */
    @JvmStatic
    @BindingAdapter("gone")
    fun gone(view: View, boolean: Boolean) {
        view.isGone = boolean
    }

    /**
     * 设置view的宽度
     */
    @JvmStatic
    @BindingAdapter("width")
    fun width(view: View, width: Int) {
        view.apply {
            val params = layoutParams ?: ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            params.width = width
            layoutParams = params
        }
    }
}